﻿using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.IO;
using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;

namespace Pay.H5.Controllers {
    [AppAuthorize("Member")]
    public class UserController : GeneralController {
        public UserController() { }
        private IMerchantService _merchantService;
        private IShippingAddressService _shippingAddressService;
        private IRegionService _iRegionService;
        private ICollectService _collectService;
        private IBillService _iBillService;
        private IGradeService _iGradeService;
        private ICartService _iCartService;
        private IOrderService _iOrderService;

        public UserController(IMerchantService merchantService, ICollectService collectService,
                              IShippingAddressService shippingAddressService, IRegionService iRegionService,
                              IBillService iBillService, IGradeService iGradeService, IOrderService iOrderService,
                              ICartService iCartService) {
            _merchantService = merchantService;
            _shippingAddressService = shippingAddressService;
            _iRegionService = iRegionService;
            _collectService = collectService;
            _iBillService = iBillService;
            _iGradeService = iGradeService;
            _iCartService = iCartService;
            _iOrderService = iOrderService;

        }
        #region 移除收藏
        public JsonResult DelCollect(long ProductId) {
            int result = _collectService.DelCollect(UserId, ProductId);
            if (result <= 0) {
                api_result.result_code = 500;
                api_result.result_msg = "操作异常";
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 我的收藏
        public ActionResult Collect() {
            var list = _collectService.GetCollects(UserId);
            ViewData["list"] = list;
            return View();
        }
        #endregion
        /// <summary>
        /// 个人信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public ActionResult PersonInfo() {
            var user = _merchantService.Get(UserId);
            ViewData["user"] = user;
            ViewData["url"] = site.img_url;
            return View();
        }
        public ActionResult Set() {
            return View();
        }
        /// <summary>
        /// 用户中心
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActionResult UserInfo() {
            var model = _merchantService.Get(UserId);
            var grade = _iGradeService.Get(model.grade_id ?? 0);
            ViewData["model"] = model;
            ViewData["gradeName"] = (grade == null ? "" : grade.name);
            ViewData["url"] = site.img_url;
            return View();
        }

        #region 修改昵称
        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <returns>The name.</returns>
        public ActionResult UpdateName() {
            var model = _merchantService.Get(UserId);
            ViewData["model"] = model;
            return View();
        }
        /// <summary>
        /// 修改用户名
        /// </summary>
        /// <returns>The update.</returns>
        /// <param name="UserName">User name.</param>
        public JsonResult Update(string UserName) {
            var result = _merchantService.SaveUserNickName(UserName, UserId, Models.RequestMethodh5.MerchantNO);
            if (!result) {
                api_result.result_code = 500;
                api_result.result_msg = "操作异常";
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 收货地址管理
        /// <summary>
        /// 收货地址列表
        /// </summary>
        /// <returns>The list.</returns>
        public ActionResult AdressList() {
            var list = _shippingAddressService.GetByUser(UserId);
            foreach (var item in list) {
                item.id_card = IDCardHide(item.id_card);
            }
            ViewData["list"] = list;
            return View();
        }
        /// <summary>
        /// 用户已登录【收货地址列表】
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectAdressList() {
            var list = _shippingAddressService.GetByUser(UserId);
            foreach (var item in list) {
                item.id_card = IDCardHide(item.id_card);
            }
            ViewData["list"] = list;
            return View();
        }
        /// <summary>
        /// 选择收货地址
        /// </summary>
        /// <param name="address_id"></param>
        /// <returns></returns>
        public JsonResult UpdateAddress(long address_id) {
            var orders = _iOrderService.GetOrderList(UserId);
            var dto = _shippingAddressService.Get(address_id);
            orders.ForEach(c => {
                c.shipping.address = dto.address;
                c.shipping.real_name = dto.real_name;
                c.shipping.region_name = dto.region_name;
                c.shipping.region_id = (dto.area_id == 0 ? dto.city_id : dto.area_id);
                c.shipping.id_card = dto.id_card;
                c.shipping.phone = dto.phone;
                c.shipping.ship_to = dto.ship_to;
                c.shipping.card_negative = dto.card_negative;
                c.shipping.card_positive = dto.card_positive;
            });
            _iOrderService.SetOrderList(orders, UserId);
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 收货地址【未登录】
        /// </summary>
        /// <returns>The address.</returns>
        [AllowAnonymous]
        public ActionResult AddAddress() {
            ViewData["shipping"] = new shipping_dto();
            string order_no = GetCookieValue("cache_no");
            if (!string.IsNullOrEmpty(order_no)) {
                var orders = _iOrderService.GetOrderList(order_no);
                if (orders != null)
                    ViewData["shipping"] = orders.FirstOrDefault().shipping;
            }
            return View();
        }
        /// <summary>
        /// 分润
        /// </summary>
        /// <returns>The profit.</returns>
        public ActionResult Profit() {
            var bill = _iBillService.GetByMerchant(UserId);
            ViewBag.balance = bill.balance;
            return View();
        }
        public PartialViewResult _Profit(BillQuery query) {
            query.merchant_id = UserId;
            query.bill_type = BillType.Distribution;
            var merchant = _merchantService.Get(UserId);
            var items = new List<bill_distribute>();
            var distributes = new PagedResult<bill_distribute>();
            var lists = _iBillService.GetByMerchant(query);
            foreach (var row in lists.rows) {
                var orders = _iOrderService.GetListByPayId(row.pay_id);
                foreach (var order in orders) {
                    var bind = order.binds.FirstOrDefault(c => c.merchant_no == merchant.merchant_no);
                    if (bind == null)
                        continue;
                    items.Add(new bill_distribute { amount = bind.amount, create_time = row.create_time.ToString("yyyy-MM-dd"), product_name = bind.product_name });
                }
            }
            distributes.page = lists.page;
            distributes.rows = items;
            distributes.size = lists.size;
            distributes.total_result = lists.total_result;
            return PartialView(distributes);
        }
        /// <summary>
        /// 保存收货地址
        /// </summary>
        /// <returns>The address.</returns>
        /// <param name="dto">Dto.</param>
        [AllowAnonymous]
        public JsonResult SubmitAddress(shippingaddress_dto dto) {
            if (!string.IsNullOrEmpty(dto.card_negative) && !dto.card_negative.Contains("card"))
                dto.card_negative = UploadImage("card", dto.card_negative);
            if (!string.IsNullOrEmpty(dto.card_positive) && !dto.card_positive.Contains("card"))
                dto.card_positive = UploadImage("card", dto.card_positive);
            dto.merchant_id = UserId;
            if (UserId > 0)
                _shippingAddressService.AddAddress(dto);
            string order_no = GetCookieValue("cache_no");
            object object_id = (UserId > 0 ? UserId.ToString() : order_no);
            var orders = _iOrderService.GetOrderList(object_id);
            if (orders == null) {
                api_result.result_code = 500;
                api_result.result_msg = "缓存数据失效";
                return Json(api_result, JsonRequestBehavior.AllowGet);
            }
            orders.ForEach(c => {
                c.shipping = new shipping_dto();
                var region = _iRegionService.Get(dto.region_id);
                c.shipping.id_card = dto.id_card;
                c.shipping.real_name = dto.real_name;
                c.shipping.ship_to = dto.shipto;
                c.shipping.phone = dto.phone;
                c.shipping.card_negative = dto.card_negative;
                c.shipping.card_positive = dto.card_positive;
                c.shipping.region_id = dto.region_id;
                c.shipping.region_name = (region == null ? "" : region.region_name);
                c.shipping.address = dto.address;
            });
            _iOrderService.SetOrderList(orders, object_id);

            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除收货地址
        /// </summary>
        /// <returns>The delete.</returns>
        /// <param name="Id">Identifier.</param>
        public JsonResult Delete(long Id) {
            var result = _shippingAddressService.Delete(Id);
            if (result <= 0) {
                api_result.result_code = 500;
                api_result.result_msg = "操作异常";
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 设置默认地址
        /// </summary>
        /// <returns>The default.</returns>
        /// <param name="Id">Identifier.</param>
        public JsonResult SetDefault(long Id) {
            var list = _shippingAddressService.GetByUser(UserId);
            if (list != null && list.Count > 0) {
                foreach (var item in list) {
                    item.is_default = (item.id == Id ? true : false);
                    _shippingAddressService.Update(item);
                }
            } else {
                api_result.result_code = 500;
                api_result.result_msg = "操作异常";
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 隐藏身份证号码
        /// </summary>
        /// <returns>The ard hide.</returns>
        /// <param name="card">Card.</param>
		private string IDCardHide(string card) {
            string temp = null;
            if (card.Length == 18) {
                temp = card.Substring(0, 5) + "***********" + card.Substring(16, 2);
            }
            if (card.Length == 15) {
                temp = card.Substring(0, 4) + "********" + card.Substring(12, 3);
            }
            return temp;
        }
        /// <summary>
        /// 省市区地址
        /// </summary>
        /// <returns></returns>
		[AllowAnonymous]
        public JsonResult Regions() {
            var result = _iRegionService.GetAll();
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region
        //base64图片上传
        [AllowAnonymous]
        protected string UploadImage(string action_dir, string img, bool use_time = false) {
            if (string.IsNullOrEmpty(img) || string.IsNullOrEmpty(action_dir)) return null;
            string path = string.Empty;
            var time = DateTime.Now.Date;
            var dir = string.Format("{0}", action_dir).TrimEnd('/');
            if (use_time) dir += "/" + (time.Ticks).ToString().TrimEnd('0');
            byte[] file_byte = Convert.FromBase64String(img);
            var fileType = FileValid.GetFileType(file_byte);
            if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
                throw new ServerErrorException("上传文件格式不正确");
            var type = fileType.ToString().ToLower();
            using (MemoryStream mss = new MemoryStream(file_byte)) {
                var oid = Guid.NewGuid().ToString("N");
                path = string.Format("{0}/{1}.{2}", dir, oid, type);
                var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
                var ok = oss.PutObject("glb-bucket", path, mss);
            }
            //释放内存
            GC.Collect();
            return path;
        }
        #endregion
    }
}